package com.wizinno.android.urineflow.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import cn.hutool.core.util.StrUtil;
import com.wizinno.android.urineflow.R;
import com.wizinno.android.urineflow.application.ExitApplication;
import com.wizinno.android.urineflow.constant.CommonConstant;
import com.wizinno.android.urineflow.constant.CommonControl;
import com.wizinno.android.urineflow.constant.MessageInfo;
import com.wizinno.android.urineflow.data.ErrorCodeEnum;
import com.wizinno.android.urineflow.service.MQTTService;
import com.wizinno.android.urineflow.thread.UsbInitThread;
import com.wizinno.android.urineflow.util.CommonUtil;
import com.wizinno.android.urineflow.util.FileUtil;
import com.wizinno.android.urineflow.util.LogUtils;
import com.wizinno.android.urineflow.util.ToastUtil;
import lombok.Getter;

import java.util.ArrayList;
import java.util.List;

@Getter
public class MainActivity extends BaseActivity {

    private static TextView tv_device_company;
    private static TextView tv_device_sn;
    private ImageView iv_wifi;

    //称重数据
    public static List<Float> weightList;
    //尿流率
    public static List<Float> rateList;

    IntentFilter wifiIntentFilter;

    final int STORAGE_PERMISSION_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ExitApplication.getInstance().addActivity(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_device_company = findViewById(R.id.tv_device_company);
        tv_device_sn = findViewById(R.id.tv_device_sn);
        iv_wifi = findViewById(R.id.iv_wifi);

        wifiIntentFilter = new IntentFilter();
        wifiIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);

        initData();
    }

    private void initData() {
        setDeviceInfo();
        CommonControl.INSTANCE.handler = handler;
        CommonControl.INSTANCE.mainActivity = this;
        weightList = new ArrayList<>();
        rateList = new ArrayList<>();
        startService(new Intent(MainActivity.this, MQTTService.class));
        //获取存储权限
        verifyStoragePermissions();
        toHome(true);
    }

    private void usbInit() {
        //先创建存储文件夹
        FileUtil.createDir();
        LogUtils.createDir();
        CommonControl.INSTANCE.isStoragePermission = true;
        UsbInitThread usbThread = new UsbInitThread();
        usbThread.start();
    }

    public void verifyStoragePermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                //没有权限则申请权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
            } else {
                usbInit();
            }
        } else {
            usbInit();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case STORAGE_PERMISSION_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    CommonControl.INSTANCE.isStoragePermission = true;
                    //申请权限成功
                    usbInit();
                } else {
                    CommonControl.INSTANCE.isStoragePermission = false;
                    ToastUtil.showLong(this, "存储权限申请失败,请重新授权");
                    verifyStoragePermissions();
                }
                break;
        }
    }

    private void setDeviceInfo() {
        String sn = CommonUtil.getMacDefault();
        CommonControl.INSTANCE.DEVICE_SN = sn;
        CommonConstant.setPrefix(sn);
        String company = FileUtil.readDeviceCompany();
        tv_device_company.setText(company);
        tv_device_sn.setText(sn);
//        new Thread(() -> {
//            Device deviceInfo = ServerUtil.getDeviceInfo();
//            if (deviceInfo != null) {
//                String deviceSn = deviceInfo.getSn();
//                Message msg = new Message();
//                Bundle data = new Bundle();
//                if (StrUtil.isNotBlank(deviceSn)) {
//                    String snShow = "#设备ID " + deviceSn + "#";
//                    data.putString(MessageInfo.KEY_DEVICE_SN, snShow);
//                    msg.setData(data);
//                }
//                Hospital hospital = deviceInfo.getHospital();
//                if (hospital != null) {
//                    String name = hospital.getName();
//                    if (StrUtil.isNotBlank(name)) {
//                        data.putString(MessageInfo.KEY_DEVICE_COMPANY, name);
//                    }
//                }
//                handler.sendMessage(msg);
//            }
//        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MessageInfo.WHAT_DEVICE_INFO:
                    setDeviceInfo(msg.getData());
                    break;
                case MessageInfo.WHAT_USB_DATA:
                    handleUsbData(msg.getData());
                    break;
                case MessageInfo.WHAT_ERROR:
                    handlerErrorInfo(msg.getData());
                    break;
                case MessageInfo.WHAT_MQTT_STATE:
                    SystemSettingActivity.setMqttState();
            }
        }
    };

    private void handlerErrorInfo(Bundle data) {
        int errorCode = data.getInt(MessageInfo.KEY_ERROR_CODE);
        ToastUtil.showLong(this, ErrorCodeEnum.getDesc(errorCode));
        if (ErrorCodeEnum.NO_USB_DEVICE.equals(errorCode)) {
            //todo 错误处理
        }
//        Intent intent = new Intent(MainActivity.this, ErrorActivity.class);
//        Bundle bundle = new Bundle();
//        bundle.putInt(MessageInfo.KEY_ERROR_CODE, errorCode);
//        intent.putExtras(bundle);
//        startActivity(intent);
    }

    private static void setDeviceInfo(Bundle data) {
        String sn = data.getString(MessageInfo.KEY_DEVICE_SN);
        String company = data.getString(MessageInfo.KEY_DEVICE_COMPANY);
        if (StrUtil.isNotBlank(sn)) {
            tv_device_sn.setText(sn);
        }
        if (StrUtil.isNotBlank(company)) {
            tv_device_company.setText(company);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 注册wifi消息处理器
        registerReceiver(wifiIntentReceiver, wifiIntentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(wifiIntentReceiver);
    }

    private BroadcastReceiver wifiIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
            switch (wifiState) {
                case WifiManager.WIFI_STATE_DISABLING:
                case WifiManager.WIFI_STATE_DISABLED:
                case WifiManager.WIFI_STATE_UNKNOWN:
                    iv_wifi.setImageLevel(0);
                    break;
                case WifiManager.WIFI_STATE_ENABLING:
                case WifiManager.WIFI_STATE_ENABLED:
                    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
                    int level = wifiManager.calculateSignalLevel(wifiManager.getConnectionInfo().getRssi(), 4);
                    iv_wifi.setImageLevel(level);
                    break;
            }
        }
    };

    public void toPassword(View view) {
        Intent intent = new Intent(MainActivity.this, PasswordActivity.class);
        startActivity(intent);
    }

}


